#!/usr/bin/php
<?php
/***************************************************************************
 *
 *   copyright            : (C) 2005 Winds of Storm
 *
 *   $Id: timers.php,v 1.6 2005/12/13 20:07:45 nathan Exp $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

require(dirname(__FILE__) . "/../config.php");
$skip_header = 1;
require($libdir . "init." . $phpEx);
require($libdir . "chat_functs." . $phpEx);

if (!isset($config['CRON_MINUTE_INTERVAL'])) {
    $sql    = "INSERT INTO ${dbprefix}events (user_id_from, room_id_to, event_text, event_date, event_chat_flags) VALUES (0, -1, '<b>ERROR: CRON_MINUTE_INTERVAL is not defined in the database and the session script is running via cron...</b>', NOW(), 2)";
    $db->sql_query($sql);
    exit;
}

function expire_session($msg, $db, $row) {
    global $dbprefix;

    $msg    = addslashes($msg);

    addToLog("Expiring session for {$row['username']}... pull_timer = {$row['pull_timer']}, idle_timer = {$row['idle_timer']}, user_id = {$row['user_id']}, room_id = {$row['room_id']}", -1, LOG_CRIT);
    print("Expiring session for {$row['username']}... pull_timer = {$row['pull_timer']}, idle_timer = {$row['idle_timer']}\n");

    //
    // Check for a newer session in the same room, if so, skip messages...
    //
    $sql    = "SELECT * FROM ${dbprefix}sessions WHERE user_id={$row['user_id']} AND room_id={$row['room_id']} AND session_time>{$row['session_time']}";
    //print("SQL = $sql\n");
    $res    = $db->sql_query($sql);
    
    if ($res == '' || $db->sql_numrows($res) > 0) {
        // 
        // They have not pulled events recently... browser window was probably closed. Boot them.
        //
        $sql    = "INSERT INTO ${dbprefix}events (user_id_from, room_id_to, event_text, event_date, event_chat_flags) VALUES ({$row['user_id']}, {$row['room_id']}, '$msg', NOW(), 2)";
        //print("SQL = $sql\n");
        $res2   = $db->sql_query($sql);
    }
    $sql    = "DELETE FROM ${dbprefix}sessions WHERE session_id='{$row['session_id']}'";
    //print("SQL = $sql\n");
    $res2   = $db->sql_query($sql);
}

//
// Increment idle timer to allow for graceful timeouts of users.
//
$sql    = "UPDATE ${dbprefix}sessions SET idle_timer=idle_timer+(60*${config['CRON_MINUTE_INTERVAL']})";
$result = $db->sql_query($sql);

//
// Update the pull timer. Basically when someone queries events.php for client pull or SlimChat,
// it resets this timer to 0. If the timer keeps incrementing, that indicates that they are not
// actually pulling new events. Most common cause of this is the user closed the browser window
// without logging out of chat.
//
// Bad users. No cookie.
//
$sql    = "UPDATE ${dbprefix}sessions SET pull_timer=pull_timer+(60*${config['CRON_MINUTE_INTERVAL']}) WHERE server_push NOT IN (4,5)";
$result = $db->sql_query($sql);

//
// Clean up logged out sessions after they would see the message about being disconnected.
//
$sql    = "DELETE FROM ${dbprefix}sessions WHERE room_id < 0 AND idle_timer > ${config['TIME_TIMEOUT']}";
$result = $db->sql_query($sql);

//
// Clean up idlers and closed client pull / slimchat sessions who are not moderators.
//
$sql    = "SELECT * FROM ${dbprefix}sessions WHERE server_push NOT IN (4,5)";
if ($result = $db->sql_query($sql)) {
    while ($row = $db->sql_fetchrow($result)) {
        //
        // Just in case they have updated the code but not ran update.php...
        //
        if (!isset($config['TIME_NOPULL'])) {
            $config['TIME_NOPULL']  = 300;
        }

        if ($row['pull_timer'] > $config['TIME_NOPULL'] && ($row['moderator'] != 1 || ($row['moderator'] == 1 && $row['server_push'] != MODE_SLIMCHAT))) {
            // 
            // They have not pulled events recently... browser window was probably closed. Boot them.
            //
            expire_session("<i>*** {$row['username']} has timed out.</i>", $db, $row);
        } else if (($row['idle_timer'] > $config['TIME_TIMEOUT']) && ($row['moderator'] != 1)) {
            // 
            // They have passed the idle timer... expire them.
            //
            expire_session("<i>*** {$row['username']} has idled out.</i>", $db, $row);
        } else {
            //
            // Implement other timeout values for warnings that were previously server-push only
            //
            if (($row['idle_timer'] > $config['TIME_WARN']) && ($row['idle_warning'] < 3) && ($row['moderator'] != 1)) {
                $sql    = "INSERT INTO {$dbprefix}events (user_id_from, room_id_to, user_id_to, event_text, event_date) VALUES (0, 0, {$row['user_id']}, '<b>+++ You will time out from inactivity in 10 minutes.</b>', NOW())";
                $db->sql_query($sql);
                $sql    = "UPDATE {$dbprefix}sessions SET idle_warning=3 WHERE session_id='{$row['session_id']}'";
                $db->sql_query($sql);
            } else if (($row['idle_timer'] > $config['TIME_LIMBO']) && ($row['idle_warning'] < 2)) {
                $sql    = "INSERT INTO {$dbprefix}events (user_id_from, room_id_to, user_id_to, event_text, event_date) VALUES ({$row['user_id']}, {$row['room_id']}, {$row['user_id']}, '<i>*** {$row['username']} has gone into limbo.</i>', NOW())";
                $db->sql_query($sql);
                $sql    = "UPDATE {$dbprefix}sessions SET idle_warning=2 WHERE session_id='{$row['session_id']}'";
                $db->sql_query($sql);
            } else if (($row['idle_timer'] > $config['TIME_IDLE']) && ($row['idle_warning'] < 1)) {
                $sql    = "INSERT INTO {$dbprefix}events (user_id_from, room_id_to, user_id_to, event_text, event_date) VALUES ({$row['user_id']}, {$row['room_id']}, {$row['user_id']}, '<i>*** {$row['username']} has become idle.</i>', NOW())";
                $db->sql_query($sql);
                $sql    = "UPDATE {$dbprefix}sessions SET idle_warning=1 WHERE session_id='{$row['session_id']}'";
                $db->sql_query($sql);
            }
        }
    }
}

